package com.zxl.designpattern.creator.factory.abstractpattern;

import java.io.InputStream;
import java.util.*;

/**
 * @author zxl
 * @version 1.0
 * @description 抽象工厂商店
 * @date 2025/5/31 18:56
 */
public class AbstractFactoryStore {

    /**
     * 根据品牌获取工厂对象
     * @param brand 品牌名称
     * @return
     */
    public static IAbstractFactory getFactory(String brand) {
        return switch (brand.toUpperCase()) {
            case "MI" -> new XiaomiFactory();
            case "HW" -> new HuaweiFactory();
            default -> throw new IllegalArgumentException("未知品牌: " + brand);
        };
    }
    /********************    下面是采用配置文件初始化工厂的模式   *********************************/
    /**
     * 定义一个Properties对象
     *
     * testFactoryPattern.properties 配置如下
     * MI=com.zxl.designpattern.creator.factory.abstractpattern.XiaomiFactory
     * HW=com.zxl.designpattern.creator.factory.abstractpattern.HuaweiFactory
     */
    private final static Map<String,IAbstractFactory> map = new HashMap();

    /**
     *
     * 根据属性配置文件中配置的内容，完成对象创建
     * 在静态代码块中，创建对象
     */
    static {
        Properties p = new Properties();
        InputStream is = AbstractFactoryStore.class.getClassLoader().getResourceAsStream("testFactoryPattern.properties");

        try {
            System.out.println("加载配置文件内容");
            p.load(is);
            //遍历Properties集合对象
            Set<Object> keys = p.keySet();
            for (Object key : keys) {
                //根据键获取值（全类名）
                String className = p.getProperty((String) key);
                //获取字节码对象
                Class clazz = Class.forName(className);
                IAbstractFactory obj = (IAbstractFactory) clazz.newInstance();
                map.put((String)key,obj);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static IAbstractFactory getFactory2(String name) {
        if(Optional.ofNullable(name).isPresent()){
            return map.get(name.toUpperCase());
        }
        return null;
    }
}
